//
//  RegistViewController.m
//  UserUse
//
//  Created by angra on 16/10/12.
//  Copyright © 2016年 CJPC. All rights reserved.
//

#import "RegistViewController.h"
#import "LLModificationViewController.h"
@interface RegistViewController ()
{
    BOOL _isAgree;
}
@property (nonatomic,weak)UIButton *registBtn;
@property (nonatomic,retain)dispatch_source_t timer;
@property (nonatomic,weak)UITextField *phoneTF;
@property (nonatomic,weak)UITextField *codeTF;
@property (nonatomic,weak)UITextField *passwordTF;



@end

@implementation RegistViewController


#pragma mark lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    self.view.backgroundColor = [UIColor whiteColor];
    [self setNavigation];
    [self setInterface];
}

-(void)setNavigation
{
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:[UIButton new]];
    self.navigationItem.leftBarButtonItem = leftItem;
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [rightBtn setTitle:@"登录" forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(popLoginVC) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -20);
    [rightBtn setTitleColor:[UIColor colorWithHexString:@"999999"] forState:UIControlStateNormal];
    UIBarButtonItem *rightItem =[[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
  
}
-(void)popLoginVC
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setInterface
{
    UIImageView *phoneImage = [[UIImageView alloc]init];
    phoneImage.image = [UIImage imageNamed:@"cellphonenumber"];
    [self.view addSubview:phoneImage];
    [phoneImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(kScaleNum(33));
        make.size.mas_equalTo(CGSizeMake(kScaleNum(10), kScaleNum(16)));
        make.left.equalTo(self.view).with.offset(kScaleNum(35));
    }];
    
    UITextField *phoneTF = [[UITextField alloc]init];
    [phoneTF addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
    phoneTF.placeholder = @"请输入11位手机号码";
    phoneTF.tag = 300;
    phoneTF.keyboardType = UIKeyboardTypePhonePad;
    phoneTF.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:phoneTF];
    [phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(phoneImage.mas_right).with.offset(kScaleNum(18));
        make.height.equalTo(phoneImage);
        make.right.equalTo(self.view).with.offset(-kScaleNum(35));
        make.bottom.equalTo(phoneImage.mas_bottom).with.offset(1);
    }];
    _phoneTF = phoneTF;
    
    UIView *lineView1 = [[UIView alloc]init];
    lineView1.backgroundColor = [UIColor colorWithHexString:@"e5e5e5"];
    [self.view addSubview:lineView1];
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(phoneImage.mas_left);
        make.right.equalTo(phoneTF.mas_right);
        make.height.equalTo(@1);
        make.top.equalTo(phoneImage.mas_bottom).with.offset(5);
    }];
    
    UIImageView *codeImage = [[UIImageView alloc]init];
    codeImage.image = [UIImage imageNamed:@"password"];
    [self.view addSubview:codeImage];
    [codeImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView1.mas_bottom).with.offset(kScaleNum(20));
        make.size.mas_equalTo(CGSizeMake(kScaleNum(12), kScaleNum(16)));
        make.left.equalTo(self.view).with.offset(kScaleNum(35));
    }];
    
    UITextField *codeTF = [[UITextField alloc]init];
    [codeTF addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
    codeTF.placeholder = @"请输入收到的数字验证码";
    codeTF.tag = 301;
    codeTF.font = [UIFont systemFontOfSize:14];
    codeTF.keyboardType = UIKeyboardTypePhonePad;
    [self.view addSubview:codeTF];
    [codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(codeImage.mas_right).with.offset(kScaleNum(15));
        make.height.equalTo(codeImage);
        make.right.equalTo(self.view).with.offset(-kScaleNum(35)-kScaleNum(125/2));
        make.bottom.equalTo(codeImage.mas_bottom).with.offset(1);
    }];
    _codeTF = codeTF;
    
    UIView *lineView2 = [[UIView alloc]init];
    lineView2.backgroundColor = [UIColor colorWithHexString:@"e5e5e5"];
    [self.view addSubview:lineView2];
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(codeImage.mas_left);
        make.right.equalTo(lineView1.mas_right);
        make.height.equalTo(@1);
        make.top.equalTo(codeImage.mas_bottom).with.offset(5);
    }];
    
    UIButton *codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    codeBtn.backgroundColor = [UIColor colorWithHexString:@"cccccc"];
    [codeBtn addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
    [codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [codeBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    codeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:codeBtn];
    [codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(lineView1);
        make.width.equalTo(@(kScaleNum(125/2)));
        make.height.equalTo(@(kScaleNum(24)));
        make.bottom.equalTo(lineView2.mas_top).with.offset(-kScaleNum(9/2));
    }];
    
    UIImageView *passwordImage = [[UIImageView alloc]init];
    passwordImage.image = [UIImage imageNamed:@"password"];
    [self.view addSubview:passwordImage];
    [passwordImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView2.mas_bottom).with.offset(kScaleNum(20));
        make.size.mas_equalTo(CGSizeMake(kScaleNum(12), kScaleNum(16)));
        make.left.equalTo(self.view).with.offset(kScaleNum(35));
    }];
    
    UITextField *passwordTF = [[UITextField alloc]init];
    [passwordTF addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
    passwordTF.placeholder = @"请输入6-20位数字字母组合密码";
    passwordTF.tag = 302;
    passwordTF.secureTextEntry = YES;
    passwordTF.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:passwordTF];
    [passwordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(passwordImage.mas_right).with.offset(kScaleNum(15));
        make.height.equalTo(passwordImage);
        make.right.equalTo(self.view).with.offset(-kScaleNum(35));
        make.bottom.equalTo(passwordImage.mas_bottom).with.offset(1);
    }];
    _passwordTF = passwordTF;
    
    UIView *lineView3 = [[UIView alloc]init];
    lineView3.backgroundColor = [UIColor colorWithHexString:@"e5e5e5"];
    [self.view addSubview:lineView3];
    [lineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(passwordImage.mas_left);
        make.right.equalTo(passwordTF.mas_right);
        make.height.equalTo(@1);
        make.top.equalTo(passwordImage.mas_bottom).with.offset(5);
    }];
    
    UIButton *agreeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [agreeBtn addTarget:self action:@selector(agreeUserDelegate:) forControlEvents:UIControlEventTouchUpInside];
    agreeBtn.layer.borderWidth = 1;
    agreeBtn.layer.borderColor = [UIColor colorWithHexString:@"999999"].CGColor;
    [self.view addSubview:agreeBtn];
    [agreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lineView3.mas_left);
        make.top.equalTo(lineView3.mas_bottom).with.offset(kScaleNum(15));
        make.size.mas_equalTo(CGSizeMake(kScaleNum(17/2), kScaleNum(17/2)));
    }];
    
    UILabel *delegateLabel = [[UILabel alloc]init];
    delegateLabel.font = [UIFont systemFontOfSize:12];

    NSMutableAttributedString *mutStr = [[NSMutableAttributedString alloc]initWithString:@"我已阅读并同意《用户协议》" ];
    [mutStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"f3961a"] range: NSMakeRange([[mutStr string] rangeOfString:@"《用户协议》"].location, [[mutStr string] rangeOfString:@"《用户协议》"].length)];
    delegateLabel.userInteractionEnabled = YES;
    delegateLabel.attributedText = mutStr;
    [self.view addSubview:delegateLabel];
    [delegateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(agreeBtn.mas_right).with.offset(kScaleNum(10));
        make.centerY.equalTo(agreeBtn);
        make.height.equalTo(@(kScaleNum(12)));
        make.width.equalTo(@(kScaleNum(165)));
    }];

    
    UIButton *tapBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    tapBtn.backgroundColor = [UIColor clearColor];
    [tapBtn addTarget:self action:@selector(userDelegateClick) forControlEvents:UIControlEventTouchUpInside];
    [delegateLabel addSubview:tapBtn];
    [tapBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(delegateLabel);
        make.height.equalTo(delegateLabel);
        make.width.equalTo(@(kScaleNum(330/4)));
        make.top.equalTo(delegateLabel);
    }];
    
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [registBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registBtn addTarget:self action:@selector(registClick) forControlEvents:UIControlEventTouchUpInside];
    [registBtn setTitleColor:[UIColor colorWithHexString:@"cccccc"] forState:UIControlStateNormal];
    registBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    registBtn.backgroundColor = [UIColor whiteColor];
    registBtn.layer.borderWidth = 1;
    registBtn.layer.borderColor = [UIColor colorWithHexString:@"cccccc"].CGColor;
    registBtn.layer.cornerRadius = kScaleNum(30)/2;
    registBtn.clipsToBounds = YES;
    registBtn.userInteractionEnabled = NO;
    [self.view addSubview:registBtn];
    [registBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(delegateLabel.mas_bottom).with.offset(kScaleNum(21));
        make.centerX.equalTo(self.view);
        make.height.equalTo(@(kScaleNum(30)));
        make.width.equalTo(@(kScaleNum(200)));
    }];
    _registBtn = registBtn;
    
}

-(void)agreeUserDelegate:(UIButton *)button
{
    _isAgree = !_isAgree;
    if (_isAgree) {
//        button.backgroundColor = [UIColor colorWithHexString:@"ff9a02"];
        [button setBackgroundImage:[UIImage imageNamed:@"regist_delegate"] forState:UIControlStateNormal];
        [self textFieldDidChange];
    }
    else
    {
        [button setBackgroundImage:nil forState:UIControlStateNormal];
        button.backgroundColor = kWhiteColor;
        [self textFieldDidChange];
    }
}
-(void)textFieldDidChange
{
    UITextField *phoneTF = [self.view viewWithTag:300];
    UITextField *codeTF = [self.view viewWithTag:301];
    UITextField *passwordTF = [self.view viewWithTag:302];
    if ([phoneTF.text checkTel] && codeTF.text.length == 6 && [passwordTF.text checkPassword] && _isAgree) {
        self.registBtn.backgroundColor = [UIColor colorWithHexString:@"ff9a02"];
        [self.registBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        self.registBtn.layer.borderColor = kClearColor.CGColor;
        self.registBtn.userInteractionEnabled = YES;
    }
    else
    {
        self.registBtn.backgroundColor = kWhiteColor;
        [self.registBtn setTitleColor:[UIColor colorWithHexString:@"cccccc"] forState:UIControlStateNormal];
        self.registBtn.layer.borderColor = [UIColor colorWithHexString:@"cccccc"].CGColor;
        self.registBtn.userInteractionEnabled = NO;
    }
}
-(void)getCode:(UIButton *)button
{
    if (![self.phoneTF.text checkTel]) {
        showAlert(nil, @"手机号格式不正确");
        return;
    }
    
    button.userInteractionEnabled = NO;
    __block int time = 60;
    NSTimeInterval period = 1.0;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
             time--;
            [button setTitle:[NSString stringWithFormat:@"%ds",time] forState:UIControlStateNormal];
           
            if (time == -1) {
                if(_timer){
                    dispatch_source_cancel(_timer);
                    _timer = nil;
                }
                 button.userInteractionEnabled = YES;
                [button setTitle:[NSString stringWithFormat:@"重发"] forState:UIControlStateNormal];
                time = 10;
            }
        });
      
    });
    dispatch_resume(_timer);
    
 
    [AllProjectRequest codeWithUserPhone:self.phoneTF.text success:^(id responseObject) {
        
    } failure:^(NSString *error) {
        
    }];
    

}
-(void)registClick
{
  
    [AllProjectRequest registWithUserPhone:self.phoneTF.text userpwd:self.passwordTF.text mobileCode:self.codeTF.text success:^(id responseObject){
        if (isSuccessRequest) {
//            [AllProjectRequest loginWithUserPhone:self.phoneTF.text userpwd:self.passwordTF.text userType:@"1" success:^(id responseObject) {
//                NSString * massage = responseObject[@"resultMassage"];
//                if ([massage isEqualToString:@"登录成功"]) {
//                    LLUserModel *user = [LLUserModel new];
//                    user.UserTelephone = self.phoneTF.text ;
//                    user.passWord = self.passwordTF.text;
//                    user.UserName = responseObject[@"resultObject"][@"username"];
//                    user.userid = [NSString stringWithFormat:@"%@",responseObject[@"resultObject"][@"userid"]];
//                    user.UserIconUrl = responseObject[@"resultObject"][@"userheadpath"];
//                    [LLUserHandle saveUserDataWith:user];
//                    [self.navigationController popToRootViewControllerAnimated:YES];
//                }
            
//            
//            } failure:^(NSString *error) {
//                
//            }];
            LLUserModel *user = [LLUserModel new];
            user.UserTelephone = self.phoneTF.text ;
            user.passWord = self.passwordTF.text;
            [LLUserHandle saveUserDataWith:user];
            LLModificationViewController *modification = [[LLModificationViewController alloc]init];
            [self.navigationController pushViewController:modification animated:YES];
        }
        else{
            [MBProgressHUD showTheMessage:responseObject[@"resultMassage"] with:nil];
        
        }
        
    } failure:^(NSString *error) {
        
    }];
   

}
-(void)userDelegateClick
{


}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
